package com.zyz.O_网络编程.TCP.single;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author: vick
 * @Date: 2025/4/15
 * @Description:
 * @version: 1.0
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //1. 创建Socket对象，连接服务器
        Socket socket = new Socket("192.168.0.106", 8888);

        //2.获取输出流，发送数据个服务端
        OutputStream outputStream = socket.getOutputStream();
        //发送数据
        outputStream.write("hello".getBytes());
        //在流末尾写入一个标记，对方才能读到-1，否则对方的读取方法一直堵塞
        socket.shutdownOutput();

        //3. 获取输入流，接收服务端返回的消息
        InputStream inputStream = socket.getInputStream();

        //定义字节数组
        byte[] data = new byte[1024];
        StringBuilder str = new StringBuilder();
        int len;
        //循环读取
        while ((len = inputStream.read(data)) != -1) {
            str.append(new String(data, 0, len));
        }
        System.out.println("服务端返回的消息是：" + str);

        //4. 关闭socket
        socket.close();
    }
}
